
#include <stdint.h>
#include "Contract.h"
#include "IO.h"

#define NUM_X	3
#define NUM_Y	4

static const IO_T keyPinY[NUM_Y] = {
	IO_INIT_TABLE(GPIOC, GPIO_PIN_3),
	IO_INIT_TABLE(GPIOC, GPIO_PIN_2),
	IO_INIT_TABLE(GPIOC, GPIO_PIN_1),
	IO_INIT_TABLE(GPIOC, GPIO_PIN_0),
};

static const IO_T keyPinX[NUM_X] = {
	IO_INIT_TABLE(GPIOC, GPIO_PIN_4),
	IO_INIT_TABLE(GPIOC, GPIO_PIN_5),
	IO_INIT_TABLE(GPIOC, GPIO_PIN_6),
};

static const IO_T keyBacklight = IO_INIT_TABLE(GPIOA, GPIO_PIN_2);


void BSP_Keyboard_Backlight_Set(uint8_t state){
	IO_Set(&keyBacklight, state);
}

static void BSP_Keyboard_BacklightInit(void){
	IO_Init(&keyBacklight, IO_Mode_OUT);
}

/*
初始化一组IO
*/
static void BSP_PinGroup_Init(const IO_T *io, uint8_t num, uint32_t mode){
	uint8_t i;
	
	for(i = 0; i < num; i++){
		IO_Init(&io[i], mode);
	}
}

static void BSP_PInGroup_Set(const IO_T *io, uint8_t num, uint8_t state){
	uint8_t i;
	
	for(i = 0; i < num; ++i){
		IO_Set(&io[i], state);
	}
}

static int BSP_PinGroup_Scan(const IO_T *io, uint8_t num, uint8_t state){
	uint8_t i;
	
	for(i = 0; i < num; ++i){
		if(IO_Get(&io[i]) == state){
			return i;
		}
	}
	
	return -1;	
}


void BSP_Keyboard_Init(void){
	BSP_Keyboard_BacklightInit();
	BSP_Keyboard_Backlight_Set(1);
	BSP_PinGroup_Init(keyPinY, NUM_Y, IO_Mode_IPU);
	BSP_PinGroup_Init(keyPinX, NUM_X, IO_Mode_IPU);
	//初始化IO状态
	BSP_PInGroup_Set(keyPinY, NUM_Y, 1);
}


static const char keyMap[NUM_X][NUM_Y] = {
	[0] = {'#', 0, 9, '*'},
	[1] = {8, 7, 6, 5},
	[2] = {4, 3, 2, 1},
};


int BSP_Keyboard_Scan(void){
	int x;
	int y;
	int key;
	
	for(y = 0; y < NUM_Y; ++y){
		
		IO_Init(&keyPinY[y], IO_Mode_OUT);
		IO_Set(&keyPinY[y], 0);
		x = BSP_PinGroup_Scan(keyPinX, NUM_X, 0);
		IO_Set(&keyPinY[y], 1);
		IO_Init(&keyPinY[y], IO_Mode_IPU);
		if(x >= 0){
			key = keyMap[x][y];
			return key;
		}
	}
	return -1;
}

void BSP_Keyboard_Lock(uint8_t state){

}



